package au.com.handsunited.model.validators.contactinfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import au.com.handsunited.model.Address;
import au.com.handsunited.model.ContactInfo;
import au.com.handsunited.model.validators.address.AddressValidator;

/**
 * @author arunda
 *
 */
public class ContactInfoValidator implements Validator {

	private final AddressValidator addressValidator;

	private static Logger logger = LoggerFactory.getLogger(ContactInfoValidator.class);


	public ContactInfoValidator (AddressValidator addressValidator) {
		if (addressValidator == null) {
			throw new IllegalArgumentException("The supplied AddressValidator is required and must not be null.");
		}

		if (!addressValidator.supports(Address.class)) {
			throw new IllegalArgumentException("The supplied AddressValidator must support the validation of Address instances.");
		}

		this.addressValidator = addressValidator;
	}

	/**
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class clazz) {
		return clazz.isAssignableFrom(ContactInfo.class);
	}

	/**
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	@Override
	public void validate(Object target, Errors errors) {

		ContactInfo contactInfo = (ContactInfo) target;

		try {
			errors.pushNestedPath("address");
			ValidationUtils.invokeValidator(addressValidator, contactInfo.getAddress(), errors);
		} finally {
			errors.popNestedPath();
		}
	}

}
